package kz.pdt12.hw.framework;

import kz.pdt12.hw.data.ContactData;
import kz.pdt12.hw.utils.SortedListOf;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

/**
 * Created with IntelliJ IDEA.
 * User: raimbek
 * Date: 21.03.13
 * Time: 20:05
 */
public class PrintPhonesHelper extends WebDriverHelperBase {

    private String xpathTable = ".//table[@id='view']/tbody";
    private String xpathRows = xpathTable + "/tr";
    private int countColumns = 3;

    public PrintPhonesHelper(ApplicationManager manager) {
        super(manager);
    }

    public SortedListOf<ContactData> getContacts() {
        manager.navigateTo().printPhones();

        SortedListOf<ContactData> contacts = new SortedListOf<ContactData>();

        for (int i = 0; i < getCountRows(); i++) {
            for (int j = 0; j < countColumns; j++) {
                ContactData contact = getContactFromTable(i, j);
                if (contact != null) {
                    contacts.add(contact);
                }
            }
        }

        return contacts;
    }

    public int getCountRows() {
        return driver.findElements(By.xpath(xpathRows)).size();
    }

    public ContactData getContactFromTable(int row, int column) {
        row++;
        column++;
        String xpathCell = xpathRows + "[" + row + "]/td[" + column + "]";
        WebElement cell = driver.findElement(By.xpath(xpathCell));
        String text = cell.getText();

        if (text.equals(".")) {
            return null;
        }

        String[] contactText = text.split("\\n");

        String telephoneHome = "";
        for (String ct : contactText) {
            if (ct.startsWith("H: ")) {
                telephoneHome = ct.replace("H: ", "");
                break;
            }
        }

        ContactData contact = new ContactData();

        String name = contactText[0];
        name = name.substring(0, name.length() - 1);
        if (name.matches("^[^ ]* $")) {
            contact.setFirstName(name.trim());
        } else if (name.matches("^[^ ]*$")) {
            contact.setLastName(name);
        } else {
            contact.setFirstName(name.split("\\s")[0]);
            contact.setLastName(name.split("\\s")[1]);
        }
        contact.setTelephoneHome(telephoneHome);

        return contact;
    }
}
